package com.lxk.util;

import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * GET方法请求URL，拉取信息并解析为JSON对象
 * @author JohnSoybean
 */
public class HttpUtil {
	 public static JSONObject doGet(String url) {
		 JSONObject jsonObject = new JSONObject();
		 try {
	         URL urlGet = new URL(url);
	         HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
	         http.setRequestMethod("GET"); // 必须是get方式请求
	         http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	         http.setDoOutput(true);
	         http.setDoInput(true);
	         /*System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
	         System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 */
	         http.connect();
	         InputStream is = http.getInputStream();

			 /**
			  * 在网络流中使用is.available()时，由于数据量过大而分次传输或有延迟，将导致获取的数据不完整，不使用该方法
			  */
//	         int size = is.available();
//	         byte[] jsonBytes = new byte[size];
//	         is.read(jsonBytes);

			 /**
			  * 使用字节输出流分次读取输入流，并将结果转换为字节数组，可获取完整数据
			  */
			 ByteArrayOutputStream out = new ByteArrayOutputStream();
			 byte[] cache = new byte[1024];
			 int nRead = 0;
			 while ((nRead = is.read(cache)) != -1) {
				 out.write(cache, 0, nRead);
				 out.flush();
			 }
			 out.close();
			 is.close();
			 byte[] jsonBytes = out.toByteArray();

	         String message = new String(jsonBytes, "UTF-8");
			 System.out.println(message);
			 jsonObject = JSONObject.parseObject(message);
	     } catch (Exception e) {
		 	e.printStackTrace();
	     }
	     return jsonObject;
	 }
}
